const bcrypt = require("bcryptjs");
// 验证器
const { getUserInfo } = require("../service/user.service");
const { userFormateError, userAlreadyExited, userRegisterError, userDoesNotExist, userLoginError, invalidPassword } = require("../constant/err.type");
class User {
  async userValidator(ctx, next) {
    const { user_name, password } = ctx.request.body;
    if (!user_name || !password) {
      console.error("用户名或密码不符合", { user_name, password });
      ctx.app.emit("error", userFormateError, ctx);
      return;
    }
    await next();
  }
  async verifyUser(ctx, next) {
    const { user_name } = ctx.request.body;
    try {
      const res = await getUserInfo({ user_name });
      if (res) {
        console.error("用户名已存在", { user_name });
        ctx.app.emit("error", userAlreadyExited, ctx);
        return;
      }
    } catch (error) {
      console.error("校验用户出错", { error });
      ctx.app.emit("error", userRegisterError, ctx);
      return;
    }
    await next();
  }
  async encryptionPassword(ctx, next) {
    const { password } = ctx.request.body;
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);
    ctx.request.body.password = hash;
    await next();
  }
  async verifyLogin(ctx, next) {
    const { user_name, password } = ctx.request.body;
    try {
      const res = await getUserInfo({ user_name });
      // res 中带有了用户的信息 包含了password
      if (!res) {
        ctx.app.emit("error", userDoesNotExist, ctx);
        return;
      }
      if (!bcrypt.compareSync(password, res.password)) {
        ctx.app.emit("error", invalidPassword, ctx);
        return;
      }
    } catch (error) {
      console.error("用户登录错误", { error });
      return ctx.app.emit("error", userLoginError, ctx);
    }
    await next();
  }
}

module.exports = new User();
